<!-- eslint-disable require-atomic-updates -->
<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true" @close="btnCancel">添加角色</el-button>
        <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
          <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
            <el-form-item prop="name" label="角色名称"><el-input v-model="roleForm.name" style="width: 300px;" size="mini" /></el-form-item>
            <el-form-item label="启用"><el-switch v-model="roleForm.state" size="mini" /></el-form-item>
            <el-form-item prop="description" label="角色描述"><el-input v-model="roleForm.description" type="textarea" :rows="3" style="width: 300px;" size="mini" /></el-form-item>
            <el-form-item>
              <el-row type="flex" justify="center">
                <el-col :span="13">
                  <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
                  <el-button size="mini" @click="btnCancel">取消</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list" scoped>
        <!-- 放置列 -->
        <!-- 作用域插槽属性包括 row，column，$index和store -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <!-- {{ row.state===1?'已启用':'未启用' }}
        </el-table-column></el-table-column></el-table></div></div></template>
        </el-table-column> -->
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>  {{ row.state === 1 ? "已启用" : "未启用" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->>
              <el-button type="primary" size="mini" @click="btnEditOk(row)">确定</el-button>
              <el-button type="text" size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
                <el-tree
                  ref="permTree"
                  node-key="id"
                  :data="permissionData"
                  :props="{label:'name'}"
                  show-checkbox
                  default-expand-all
                  :default-checked-keys="permIds"
                />
                <el-row slot="footer" type="flex" justify="center">
                  <el-col :span="6">
                    <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
                    <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
                  </el-col>
                </el-row>
              </el-dialog>
              <el-button type="text" size="mini" @click="btnEditRow(row)">编辑</el-button>
              <!-- 新增一个冒泡弹窗，确定执行绑定onConfirm事件，包裹删除按钮 -->
              <el-popconfirm title="确定删除该角色吗？" @onConfirm="delRole(row.id)">
                <el-button
                  slot="reference"
                  type="text"
                  size="mini"
                  style="margin-left: 10px;"
                >删除
                </el-button>
              </el-popconfirm>

            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件
        prev 上一页 pager页码值 next下一页
        total 总条数
        page-size每页显示多少条
        current-page 当前页码
        current-change 页面值发生变化时触发
        -->
        <el-pagination
          layout="total,sizes, prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          :page-sizes="[3,5,7,9,11]"
          @current-change="changePage"
          @size-change="changeSize"
        />
      </el-row>
    </div>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { transListToTreeData } from '@/utils'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      currentRoleId: null,
      permIds: [],
      showPermissionDialog: false,
      permissionData: [], // 权限列表
      isEdit: false,
      showDialog: false,
      list: [],
      // 定义分页的查询参数，注意使用小写
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 点击确定事触发
    async  btnPermissionOK() {
      // console.log(this.permIds)
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    },
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(this.currentRoleId)
      this.permIds = permIds // 获取权限列表数据 并且转树型
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true // 显示弹层
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 切换分页时 调用
    changePage(newPage) {
      // （形参）newPage表示最新的页码值
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList() // 重新获取当前页数据
    },
    changeSize(newpSize) {
      this.pageParams.pagesize = newpSize
      this.getRoleList()
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功~')
          this.btnCancel() // 重置表单 移除校验规则 关闭弹层
          this.getRoleList() // 重新获取数据
        }
      }
      )
    },
    btnCancel() {
      // 点击取消，重置表单为默认状态
      this.roleForm = {
        name: '',
        description: '',
        state: 0
      }
      // 重置表单 并移除校验规则
      this.$refs.roleForm.resetFields()
      // 关闭弹层
      this.showDialog = false
    },
    // 点击编辑行
    btnEditRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
      console.log(row)
    },
    async btnEditOk(row) {
      if (!row.editRow.name || !row.editRow.description) {
        return this.$message.error('角色名称不能为空')
      }
      await updateRole({ ...row.editRow, id: row.id })
      this.$message.success('修改角色成功')
      // 关闭编辑状态
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = false
      row.name = row.editRow.name
      row.description = row.editRow.description
      row.state = row.editRow.state
    },
    async delRole(id) {
      console.log(id)
      await delRole(id)
      this.$message.success('删除角色成功')
      // 判断当前页是否只剩下一条数据 如果只剩下一条且当前页码大于1 则把页码值-1
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      // 重新获取最新数据
      this.getRoleList()
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
